<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>
      <!-- 查询区域 -->
      <el-form
        :model="queryParams"
        ref="walletRef"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <el-form-item label="分销员" prop="distributorId">
          <el-input
            v-model="queryParams.distributorId"
            placeholder="请输入分销员ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="可用余额" prop="availableBalance">
          <el-input
            v-model="queryParams.availableBalance"
            placeholder="请输入可用余额"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="冻结余额" prop="frozenBalance">
          <el-input
            v-model="queryParams.frozenBalance"
            placeholder="请输入冻结余额"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="累计收入" prop="totalIncome">
          <el-input
            v-model="queryParams.totalIncome"
            placeholder="请输入累计收入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="累计提现" prop="totalWithdraw">
          <el-input
            v-model="queryParams.totalWithdraw"
            placeholder="请输入累计提现"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="最后入账时间" prop="lastIncomeTime">
          <el-date-picker
            clearable
            v-model="queryParams.lastIncomeTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后入账时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="最后提现时间" prop="lastWithdrawTime">
          <el-date-picker
            clearable
            v-model="queryParams.lastWithdrawTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择最后提现时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="钱包状态" prop="walletStatus">
          <el-select
            v-model="queryParams.walletStatus"
            placeholder="请选择状态：0-正常 1-冻结"
            clearable
          >
            <el-option
              v-for="dict in wallet_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="版本号" prop="version">
          <el-input
            v-model="queryParams.version"
            placeholder="请输入版本号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表单区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:wallet:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:wallet:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:wallet:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:wallet:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      border
      resizable
      stripe
      style="width: 100%"
      :data="walletList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        min-width="60"
        align="center"
        prop="walletId"
      />
      <el-table-column label="分销员" align="center" prop="distributorId" />
      <el-table-column
        label="可用余额"
        align="center"
        prop="availableBalance"
      />
      <el-table-column label="冻结余额" align="center" prop="frozenBalance" />
      <el-table-column label="累计收入" align="center" prop="totalIncome" />
      <el-table-column label="累计提现" align="center" prop="totalWithdraw" />
      <el-table-column
        label="最后入账时间"
        align="center"
        prop="lastIncomeTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastIncomeTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最后提现时间"
        align="center"
        prop="lastWithdrawTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.lastWithdrawTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="钱包状态" align="center" prop="walletStatus">
        <template #default="scope">
          <dict-tag :options="wallet_status" :value="scope.row.walletStatus" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="版本号" align="center" prop="version" /> -->
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column
        label="操作"
        min-width="150"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:wallet:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:wallet:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分销钱包对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-collapse v-model="activeCollapse">
        <!-- 钱包基本信息组 -->
        <el-collapse-item name="basic" title="钱包基本信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分销员" prop="distributorId">
                <el-select
                  v-model="form.distributorId"
                  placeholder="请选择分销员"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in distributorOptions"
                    :key="item.distributorId"
                    :label="item.distributorName + ' (' + item.mobile + ')'"
                    :value="item.distributorId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分销员编号" prop="distributorCode">
                <el-input
                  v-model="form.distributorCode"
                  placeholder="请输入分销员编号(DSN开头)"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可用余额(元)" prop="availableBalance">
                <el-input
                  v-model="form.availableBalance"
                  placeholder="请输入(如:1000.00)"
                  @input="validateAmount('availableBalance')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="冻结余额(元)" prop="frozenBalance">
                <el-input
                  v-model="form.frozenBalance"
                  placeholder="请输入(如:500.00)"
                  @input="validateAmount('frozenBalance')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="累计收入(元)" prop="totalIncome">
                <el-input
                  v-model="form.totalIncome"
                  placeholder="请输入(如:5000.00)"
                  @input="validateAmount('totalIncome')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="累计提现(元)" prop="totalWithdraw">
                <el-input
                  v-model="form.totalWithdraw"
                  placeholder="请输入(如:3000.00)"
                  @input="validateAmount('totalWithdraw')"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 钱包状态组 -->
        <el-collapse-item name="status" title="钱包状态">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="钱包状态" prop="walletStatus">
                <el-radio-group v-model="form.walletStatus">
                  <el-radio
                    v-for="dict in wallet_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="系统状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="删除标志" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio
                    v-for="dict in del_flag"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input
                  v-model="form.version"
                  disabled
                  placeholder="系统自动管理"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 时间信息组 -->
        <el-collapse-item name="time" title="时间信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最后入账时间" prop="lastIncomeTime">
                <el-date-picker
                  clearable
                  v-model="form.lastIncomeTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后提现时间" prop="lastWithdrawTime">
                <el-date-picker
                  clearable
                  v-model="form.lastWithdrawTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 分销用户信息组 -->
        <!-- <el-collapse-item name="user" title="分销用户信息">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="Plus"
                @click="handleAddDistributionUser"
                >添加</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="Delete"
                :disabled="checkedDistributionUser.length === 0"
                @click="handleDeleteDistributionUser"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <el-table
            :data="distributionUserList"
            :row-class-name="rowDistributionUserIndex"
            @selection-change="handleDistributionUserSelectionChange"
            ref="distributionUser"
            border
            style="width: 100%"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="序号"
              align="center"
              prop="index"
              width="60"
            />
            <el-table-column label="用户ID" prop="userId" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.userId" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column
              label="分销员编号"
              prop="distributorCode"
              width="150"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.distributorCode"
                  placeholder="DSN开头"
                />
              </template>
            </el-table-column>
            <el-table-column label="真实姓名" prop="realName" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.realName" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column label="手机号" prop="mobile" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.mobile" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column label="身份证号" prop="identityCard" width="180">
              <template #default="scope">
                <el-input
                  v-model="scope.row.identityCard"
                  placeholder="请输入"
                />
              </template>
            </el-table-column>
            <el-table-column label="当前等级" prop="gradeId" width="120">
              <template #default="scope">
                <el-select
                  v-model="scope.row.gradeId"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in gradeOptions"
                    :key="item.gradeId"
                    :label="item.gradeName"
                    :value="item.gradeId"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="上级分销员" prop="fatherId" width="120">
              <template #default="scope">
                <el-input
                  v-model="scope.row.fatherId"
                  placeholder="0表示无上级"
                />
              </template>
            </el-table-column>
            <el-table-column label="团队总人数" prop="teamCount" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.teamCount" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column
              label="直接下级人数"
              prop="directCount"
              width="120"
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.directCount"
                  placeholder="请输入"
                />
              </template>
            </el-table-column>
            <el-table-column label="成为分销员时间" prop="bindTime" width="160">
              <template #default="scope">
                <el-date-picker
                  clearable
                  v-model="scope.row.bindTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="最后登录时间"
              prop="lastLoginTime"
              width="160"
            >
              <template #default="scope">
                <el-date-picker
                  clearable
                  v-model="scope.row.lastLoginTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="100">
              <template #default="scope">
                <el-select v-model="scope.row.status" placeholder="请选择">
                  <el-option
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item> -->
        
        <!-- 备注信息组 -->
        <el-collapse-item name="remark" title="备注信息">
          <el-form-item label="备注信息" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              rows="3"
              placeholder="请输入钱包说明"
            />
          </el-form-item>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Wallet">
import {
  listWallet,
  getWallet,
  delWallet,
  addWallet,
  updateWallet,
} from "@/api/ruoyi/wallet";

const { proxy } = getCurrentInstance();
const { wdm_status, wallet_status, del_flag } = proxy.useDict(
  "wdm_status",
  "wallet_status",
  "del_flag"
);

const walletList = ref([]);
const distributionUserList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedDistributionUser = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    distributorId: null,
    availableBalance: null,
    frozenBalance: null,
    totalIncome: null,
    totalWithdraw: null,
    lastIncomeTime: null,
    lastWithdrawTime: null,
    walletStatus: null,
    status: null,
    version: null,
  },
  rules: {
    distributorId: [
      { required: true, message: "分销员ID不能为空", trigger: "blur" },
    ],
    availableBalance: [
      { required: true, message: "请输入可用余额", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    frozenBalance: [
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    totalIncome: [
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    totalWithdraw: [
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    walletStatus: [
      { required: true, message: "请选择钱包状态", trigger: "change" },
    ],
    status: [{ required: true, message: "请选择系统状态", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 添加响应式数据
const activeCollapse = ref(["basic", "status", "time", "user"]);

// 验证金额
function validateAmount(field) {
  return (value) => {
    if (value && !/^\d*\.?\d{0,2}$/.test(value)) {
      form.value[field] = value.match(/^\d*\.?\d{0,2}/)[0];
    }
  };
}

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 查询分销钱包列表 */
function getList() {
  loading.value = true;
  listWallet(queryParams.value).then((response) => {
    // walletList.value = response.rows
    walletList.value = response.rows.filter((item) => item.delFlag !== "2");
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    walletId: null,
    distributorId: null,
    availableBalance: null,
    frozenBalance: null,
    totalIncome: null,
    totalWithdraw: null,
    lastIncomeTime: null,
    lastWithdrawTime: null,
    walletStatus: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  distributionUserList.value = [];
  proxy.resetForm("walletRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.walletId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分销钱包";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _walletId = row.walletId || ids.value;
  getWallet(_walletId).then((response) => {
    form.value = response.data;
    distributionUserList.value = response.data.distributionUserList;
    open.value = true;
    title.value = "修改分销钱包";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["walletRef"].validate((valid) => {
    if (valid) {
      form.value.distributionUserList = distributionUserList.value;
      if (form.value.walletId != null) {
        updateWallet(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWallet(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _walletIds = row.walletId || ids.value;
  proxy.$modal
    .confirm('是否确认删除分销钱包编号为"' + _walletIds + '"的数据项？')
    .then(function () {
      return delWallet(_walletIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 分销用户信息序号 */
function rowDistributionUserIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 分销用户信息添加按钮操作 */
function handleAddDistributionUser() {
  let obj = {};
  obj.userId = "";
  obj.distributorCode = "";
  obj.realName = "";
  obj.mobile = "";
  obj.identityCard = "";
  obj.gradeId = "";
  obj.fatherId = "";
  obj.teamCount = "";
  obj.directCount = "";
  obj.bindTime = "";
  obj.lastLoginTime = "";
  obj.status = "";
  obj.remark = "";
  distributionUserList.value.push(obj);
}

/** 分销用户信息删除按钮操作 */
function handleDeleteDistributionUser() {
  if (checkedDistributionUser.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的分销用户信息数据");
  } else {
    const distributionUsers = distributionUserList.value;
    const checkedDistributionUsers = checkedDistributionUser.value;
    distributionUserList.value = distributionUsers.filter(function (item) {
      return checkedDistributionUsers.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleDistributionUserSelectionChange(selection) {
  checkedDistributionUser.value = selection.map((item) => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/wallet/export",
    {
      ...queryParams.value,
    },
    `wallet_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
</style>
